package com.example.demo.controller;

import com.example.demo.entity.*;
import com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap;
import lombok.val;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "*")
public class controller {

    @Autowired(required = false)
    private JdbcTemplate jdbc;

    @GetMapping("/sayHello") //GetMapping 定义了⼀个服务端程序，映射⽹址 /sayHello，/代表⽹址中的域名（ip）加端⼝号（根地址）
    public String testSimpleGet(){
        System.out.println("已收到");
        return "你好，SpringBoot";
    }

    @GetMapping("/say/Hi")
    public String testSimpleGet2() {
        System.out.println("已收到");
        return  "Hi!";
    }

    @GetMapping("/login")
    public  String testQueryGet(String name, Integer age) {
        System.out.println("已注册");
        return "Hello World!" + name;
    }

    @GetMapping("/login2")
    public String testQueryGet2(student s) {
        System.out.println(s);
        return "登录成功";
    }

    @GetMapping("/action/{action}/{content}")
    public String testPathVariable (@PathVariable String action, @PathVariable String content) {
        System.out.println(action);
        return content;
    }

    @PostMapping("/post")
    public String testPostJson(@RequestBody student s) {
        System.out.println(s.getName());
        return s.toString();
    }

    @PostMapping("/doLogin")
    public Result doLogin(@RequestBody Yonghu y) {
        Result result = new Result();
        try {
            result.setResult(jdbc.queryForObject("select * from yonghu where zhanghao = ? and mima = ?",
                    new BeanPropertyRowMapper<>(Yonghu.class), y.getZhanghao(), y.getMima()));
            result.setCode(200);
        } catch (DataAccessException ignored) {
            result.setResult(null);
            result.setCode(201);
        } finally {
            return result;
        }
    }

    @PostMapping("/doRegister")
    public Result doRegister(@RequestBody Yonghu y) {
        Result result = new Result();
        try {
            List<Yonghu> query = jdbc.query("select * from yonghu where zhanghao = ?",
                    new BeanPropertyRowMapper<>(Yonghu.class), y.getZhanghao());
            if(!query.isEmpty()) {
                throw new Exception() {
                    @Override
                    public String getMessage() {
                        return "已存在该账号";
                    }
                };
            }
            if(y.getMima().length() > 30) {
                throw new Exception() {
                    @Override
                    public String getMessage() {
                        return "密码过长";
                    }
                };
            }
            if(y.getMima().length() < 3) {
                throw new Exception() {
                    @Override
                    public String getMessage() {
                        return "密码过短";
                    }
                };
            }
            jdbc.update("insert into yonghu(xingming, zhanghao, mima, age, leibie) values(?,?,?,?,?)",
                    y.getXingming(), y.getZhanghao(), y.getMima(), y.getAge(), y.getLeibie());
            result.setResult(y);
            result.setCode(200);

        } catch (Exception e) {
            result.setResult(null);
            result.setCode(201);
        } finally {
            return result;
        }
    }

    @GetMapping("/dianyings")
    public Result dianyings (Integer leixingid) {
        Result result = new Result();
        try {
            if(leixingid != null) {
                List<Dianyingxinxi> query = jdbc.query("select *\n" +
                                "from dianyingxinxi\n" +
                                "where leixingid = ?",
                        new BeanPropertyRowMapper<>(Dianyingxinxi.class), leixingid);
                result.setResult(query);
                result.setCode(200);
            } else {
                List<Dianyingxinxi> query = jdbc.query("select * from dianyingxinxi",
                        new BeanPropertyRowMapper<>(Dianyingxinxi.class));
                result.setResult(query);
                result.setCode(200);
            }
        } catch (DataAccessException e) {
            result.setResult("查询失败！");
            result.setCode(201);
        } finally {
            return result;
        }
    }

    @GetMapping("/leixingtongji")
    public Result leixingtongji() {
        Result res = new Result();
        try {
            List<Leixingtongji> query = jdbc.query( "select count(*) value,leixingming name\n" +
                    "from dianyingxinxi dy join leixing lx on dy.leixingid = lx.id\n" +
                    "group by lx.id", new BeanPropertyRowMapper<>(Leixingtongji.class));
            res.setCode(200);
            res.setResult(query);
        } catch (DataAccessException e) {
            res.setCode(201);
            res.setResult(e.getMessage());
        } finally {
            return res;
        }
    }
}
